package com.kanshu.ksgb.fastread.doudou.base.basemvp;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.schedulers.ComputationScheduler;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.Subject;

/**
 * presenter基类
 * Created by wanchunyang on 17/3/17.
 */
public class BaseMvpPresenter<V extends IMvpView> implements IMvpPresenter<V> {

    public Subject<Integer> lifeCyclerSubject;

    public BaseMvpPresenter(Subject<Integer> lifeCyclerSubject) {
        this.lifeCyclerSubject = lifeCyclerSubject;
    }

    protected V mMvpView;

    @Override
    public void attachView(V view) {
        mMvpView = view;
    }

    @Override
    public void detachView() {
        mMvpView = null;
    }

    public boolean isViewAttached() {
        return mMvpView != null;
    }

    public IMvpView getMvpView() {
        return mMvpView;
    }

    public <T> ObservableTransformer<T, T> asyncRequest() {
       if(lifeCyclerSubject == null){
           return upstream -> upstream .subscribeOn(Schedulers.computation())
                   .observeOn(AndroidSchedulers.mainThread());

       }else {
        return upstream -> upstream .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .takeUntil(lifeCyclerSubject);
       }
    }

}
